package com.heo.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;

public class Utils {
	/**
	 * 字符串转换为double类型 四舍五入
	 * 
	 * @param str
	 *            字符串
	 * 
	 * @param scale
	 *            精度
	 * 
	 * @return double
	 */
	public static double stringToDouble(String str, int scale) {
		double d = 0;
		if (checkNull(str)) {
			BigDecimal l = new BigDecimal(str);
			d = l.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
		}
		return d;
	}

	/**
	 * 把byte数组转换为字符串
	 * 
	 * @param bytes
	 *            byte数组
	 * 
	 * @return string
	 */
	public static String bytesToString(byte[] bytes) {
		String strBytes = null;
		if (null != bytes && bytes.length > 0) {
			strBytes = new String(bytes);
		}
		return strBytes;
	}

	// 字符串类型的工具方法

	/**
	 * 判断字符串是否有内容 null安全
	 * 
	 * @param str
	 * 
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return StringUtils.isEmpty(str);
	}

	/**
	 * 清除字符串前后空格 null安全
	 * 
	 * @param str
	 * @return
	 */
	public static String trim(String str) {
		return StringUtils.trim(str);
	}

	/**
	 * 替换字符串所有空格、换行符、回车、制表符等
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String str) {
		String dest = "";
		if (Utils.checkNull(str)) {
			Pattern p = Pattern.compile("\\s*|t|r|n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	/**
	 * 字符串非空判断
	 * 
	 * @param str
	 * 
	 * @return boolean true:不为空; false：空
	 * 
	 * @throws FMPException
	 */
	public static boolean checkNull(Object str) {
		boolean falg = false;
		if (null != str && !"".equals(str.toString().trim())) {
			falg = true;
		}
		return falg;
	}

	/**
	 * 处理字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static String getStr(Object obj) {
		String str = "";
		if (obj != null && !"".equals(obj)) {
			str = obj.toString().trim();
		}
		return str;
	}

	/**
	 * 从String中取得Long
	 * 
	 * @param str
	 *            String参数
	 * @return Long
	 */
	public static long getLong(Object obj) {
		long lnNumber = 0;
		try {

			lnNumber = Long.parseLong(getStr(obj));
		} catch (Exception e) {
		}
		return lnNumber;
	}

	/**
	 * 把String转换为double
	 * 
	 * @param obj
	 * @return
	 */
	public static double getDouble(Object obj) {
		double d = 0;
		try {
			d = Double.parseDouble("" + obj);
		} catch (Exception e) {
		}
		return d;
	}

	/**
	 * 把String转换为double
	 * 
	 * @param obj
	 * @return
	 */
	public static int getInteger(Object obj) {
		int lnNumber = 0;
		try {

			lnNumber = Integer.parseInt(getStr(obj));
		} catch (Exception e) {
		}
		return lnNumber;
	}

	/**
	 * 把String转换为double
	 * 
	 * @param obj
	 * @return
	 */
	public static short getShort(Object obj) {
		short lnNumber = 0;
		try {

			lnNumber = Short.parseShort(getStr(obj));
		} catch (Exception e) {
		}
		return lnNumber;
	}

	/**
	 * 格式化double
	 * 
	 * @param obj
	 * @return
	 */
	public static double getDoubleFormatDouble(double obj) {
		DecimalFormat df = new DecimalFormat("######0.00");
		return new Double(df.format(obj).toString());
	}

	public static String getDoubleFormat(double account) {
		DecimalFormat df = new DecimalFormat("######0.00");
		return df.format(account);
	}

	/**
	 * 获取误差停止时间
	 * 
	 * @param time
	 * @return
	 */
	public static int getBreakTime(int time) {
		int retTime = 0;
		if (time < 10) {
			retTime = 1;
		} else {
			retTime = 2;
		}
		return retTime;
	}
	/**
	 * 取得当前时间戳（精确到分）
	 * 
	 * @return
	 */
	public static String timeStampByMinute() {
		long time = System.currentTimeMillis();
		String t = String.valueOf(time / 1000 / 60);
		return t;
	}
	/**
	 * 获取工作时间
	 * 
	 * @param time
	 * @return
	 */
	public static int getWorkTime(int workTime) {
		if (workTime > 1) {
			workTime = workTime - 1;
		} else {
			workTime = 1;
		}
		return workTime;
	}
	
	public static int getInt(Object obj) {
		int lnNumber = -1;
		try {

			lnNumber = Integer.parseInt(getStr(obj));
		} catch (Exception e) {
		}
		return lnNumber;
	}
	
	private static String xor(String strHex_X,String strHex_Y){
        //将x、y转成二进制形式   
        String anotherBinary=Integer.toBinaryString(Integer.valueOf(strHex_X,16));   
        String thisBinary=Integer.toBinaryString(Integer.valueOf(strHex_Y,16));   
        String result = "";   
        //判断是否为8位二进制，否则左补零   
        if(anotherBinary.length() != 8){   
        for (int i = anotherBinary.length(); i <8; i++) {   
                anotherBinary = "0"+anotherBinary;   
            }   
        }   
        if(thisBinary.length() != 8){   
        for (int i = thisBinary.length(); i <8; i++) {   
                thisBinary = "0"+thisBinary;   
            }   
        }   
        //异或运算   
        for(int i=0;i<anotherBinary.length();i++){   
        //如果相同位置数相同，则补0，否则补1   
                if(thisBinary.charAt(i)==anotherBinary.charAt(i))   
                    result+="0";   
                else{   
                    result+="1";   
                }   
            }  
        return Integer.toHexString(Integer.parseInt(result, 2)).toUpperCase();   
    }
	
	public static String initRechargeCheck(String balance) {
		 if(balance.length() == 4){
			String yu = balance.substring(0, 2);
			String er = balance.substring(2, 4);
			int balanceInt = Integer.parseInt(yu, 16) + Integer.parseInt(er, 16);
			String balanceStr = Integer.toHexString(balanceInt);
			int length = balanceStr.length();
			if(length > 2){
				balanceStr = balanceStr.substring(balanceStr.length() -2, balanceStr.length());
			}
			String minute = Integer.toHexString(Utils.getInt(formatDateToStr(new Date(), "mm")));
			return xor(balanceStr, minute);
		 }
		 return "";
	}
	
	/**
	 * 将短时间格式字符串转换为时间 yyyy-MM-dd
	 * 
	 * @param strDate
	 * @return
	 */
	public static Date strToDate(String strDate) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(strDate, pos);
		return strtodate;
	}

	
	/**
	 * 根据一个日期，返回是星期几的字符串
	 * 
	 * @param sdate
	 * @return
	 */
	public static String getWeek(String sdate) {
		String str = "";
		// 再转换为时间
		Date date = strToDate(sdate);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int hour = c.get(Calendar.DAY_OF_WEEK);
		if (1 == hour) {
			str = "07";
		} else if (2 == hour) {
			str = "01";
		} else if (3 == hour) {
			str = "02";
		} else if (4 == hour) {
			str = "03";
		} else if (5 == hour) {
			str = "04";
		} else if (6 == hour) {
			str = "05";
		} else if (7 == hour) {
			str = "06";
		}
		// hour中存的就是星期几了，其范围 1~7
		// 1=星期日 7=星期六，其他类推
		return str;
	}
	
	/**
	 * 将日期类型转换成指定格式字符类型
	 * 
	 * @param date
	 * @return
	 */
	public static String formatDateToStr(Date date, String dateFormat) {
		try {
			String dateStr = "";
			SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
			if (null == date) {
				return null;
			}
			dateStr = sdf.format(date);
			return dateStr;
		} catch (Exception e) {
			return null;
		}
	}
	
	public static final String FREE_STATUS = "FREE_STATUS";   //空闲状态指令
	public static final String SLOT_MATCH = "SLOT_MATCH";     //投币返回匹配指令
	public static final String SLOT_STATUS = "SLOT_STATUS";    //投币状态指令
	public static final String QUERY = "QUERY";         //状态查询指令
	public static final String START = "START";     //开始指令
	public static final String WORK_STATUS = "WORK_STATUS";    //工作状态指令
	public static final String START_MATCH = "START_MATCH";   //开始返回匹配指令
	public static final String SLOT = "SLOT";   //投币指令
	public static final String DEVICE_QUERY = "DEVICE_QUERY";         //设备轮询查询

	public static String getInitStr() {
		String sdate = formatDateToStr(new Date(), "MMyy");
		String sdd = formatDateToStr(new Date(), "dd");
		String week = getWeek(formatDateToStr(new Date(), "yyyy-MM-dd"));
		String sdates = formatDateToStr(new Date(), "ssmmHH");
		return sdates + sdd + week+ sdate;
	}
	
	public static void main(String[] args) {
		JSONObject startMsg = new JSONObject();
		startMsg.put("deviceIMEI", "0000ZHDS0000430");
		startMsg.put("commandId", 30);
		startMsg.put("deviceChannelIndex", 1);
		startMsg.put("startPara", "");
		startMsg.put("callbackPara", "a30f9fd9ef7b22b16191591a25dd563d");
		startMsg.put("appId", "a30f9fd9ef7b22b16191591a25dd563d");
		startMsg.put("callbackExpireTime", 24 * 3600);
		System.out.println(startMsg.toJSONString());
	}
}
